#!/usr/bin/perl -w

use strict;
use LWP::Simple;
use XML::Parser;

my $api="http://osmxapi.hypercube.telascience.org/api/0.6";

if (@ARGV != 2)
{
  usage();
  exit();
}

my (%relation,@ways,%ways);
$relation{id}=$ARGV[0];

#better try to open output file before downloading
open (OUT,">$ARGV[1]") || die "Can not open $ARGV[1]\n";

print "Processing $relation{id}\n";


print ("Getting $api/relation/$relation{id}...");
my $osmdata = get("$api/relation/$relation{id}");
die "\nFailed getting relation $relation{id}" unless defined $osmdata;
print "ok";


my $parser = new XML::Parser(Handlers => {Start => \&relation_tags});
$parser->parse($osmdata);
print "\n";

print "Got such ways for it: @ways\n";

$parser->setHandlers(Start => \&way_tags);

my ($way); 
my (@fetched_nodes, @current_nodes);
foreach $way (@ways) {
  print ("Getting $api/way/$way...");
  $osmdata = get("$api/way/$way");
  die "Failed getting way $way" unless defined $osmdata;
	print "ok";
  
	$parser->parse($osmdata);
	print "\n";
	print "Got such nodes for it: @current_nodes\n";

	#add @current_nodes to @fetched_nodes in such a way that they form a continous way
	unless (@fetched_nodes) {
		@fetched_nodes=@current_nodes;
	} else
	{ #check if we can simply concatenate new portion of nodes or do we need to reverse() it first?
		print "last node in fetched_nodes = $fetched_nodes[-1]\n";
		print "first node in fetched_nodes = $fetched_nodes[0]\n";
		if ($fetched_nodes[0] eq $current_nodes[0])
		{
			shift (@current_nodes);
		  @fetched_nodes = (reverse(@current_nodes),@fetched_nodes);
		} elsif ($fetched_nodes[0] eq $current_nodes[-1])
		{
			pop (@current_nodes);
			@fetched_nodes = (@current_nodes,@fetched_nodes);
		} elsif ($fetched_nodes[-1] eq $current_nodes[0])
		{
			shift (@current_nodes);
			@fetched_nodes=(@fetched_nodes,@current_nodes);
		} elsif ($fetched_nodes[-1] eq	$current_nodes[-1])
		{
			pop (@current_nodes);
			@fetched_nodes = (@fetched_nodes,reverse(@current_nodes));
		} else
		{
			die "received ways do not seem to be adjoining =(\n";
		}
	}
	@current_nodes=();
}
die "resulting polygon is not closed =(\n" unless $fetched_nodes[0] eq $fetched_nodes[-1];
print join(" ",@fetched_nodes),"\n";

#we have ids of our bounding polygon in @fetched_nodes - now we fetch lats and lons for them and dump them
$parser->setHandlers(Start => \&node_tags);

my (@coords,$node);
print OUT "1\n";
foreach $node (@fetched_nodes)
{
	print ("Getting $api/node/$node...");
	$osmdata = get("$api/node/$node");
	die "\nFailed getting node $node" unless defined $osmdata;
	print "ok";

  $parser->parse($osmdata);
  print "\n";
  print "Got such coords for it: @coords\n";
	print OUT join (" ",@coords)."\n";
}

print OUT "END\n";
close (OUT);
exit;

sub relation_tags
{
  shift; #get rid of the XML-parser-expat var
  my $element = shift;
  my %attributes;

  if ($element eq 'member')
  {
		%attributes = @_; #better use it as hash
    #print "@{[ %attributes ]}\n";
  
    if ($attributes{role} eq "") #skip (role=)enclave ways since we need to get a bounding polygon
    {
			push(@ways,$attributes{ref});
    }
  } elsif ($element eq 'tag')
	#print relation name if it has one
	{
    %attributes = @_;
		if ($attributes{k} eq "name:en") {print " (This is the $attributes{v})"}
	}
}

sub way_tags
{
  shift;
	my $element = shift;
	my %attributes;

  if ($element eq 'nd')
  {
    %attributes = @_; #better use it as hash

		#simply assign instead of pushing
		push @current_nodes,$attributes{"ref"};
  } elsif ($element eq 'tag')
  {
    %attributes = @_;
    if ($attributes{k} eq "name:en") {print " (This is the $attributes{v})"}
  }
}

sub node_tags
{
  shift;
  my $element = shift;
  my %attributes;

  if ($element eq 'node')
  {
    %attributes = @_; #better use it as hash

		@coords=($attributes{'lat'},$attributes{'lon'});
  } elsif ($element eq 'tag')
  {
    %attributes = @_;
    if ($attributes{k} eq "name:en") {print " (This is the $attributes{v})"}
  }
}

sub usage
{
  print "Usage: $0 relation_id output.poly\n";
}
